const {Group, Article, User} = require('../database/index');
const {Op} = require("sequelize");
const {ip, sendResponse} = require('../untils');

/**
 * 安全转换分页参数（确保数字类型且有合理默认值）
 * @param {any} page - 页码
 * @param {any} size - 页大小
 * @returns {Object} { page, size, offset }
 */
const parsePagination = (page, size) => {
    const currentPage = Math.max(1, parseInt(page, 10) || 1);
    const pageSize = Math.max(1, Math.min(100, parseInt(size, 30) || 30)); // 限制最大页大小
    return {
        page: currentPage,
        size: pageSize,
        offset: (currentPage - 1) * pageSize
    };
};

/**
 * 延迟函数（增加可配置性）
 * @param {number} time - 延迟毫秒数
 * @returns {Promise}
 */
const delayer = (time = 500) => {
    return new Promise(resolve => setTimeout(resolve, time));
};

// -------------------------- 路由处理函数（优化后） --------------------------

/**
 * 获取父ID树形数据
 */
const getParentIdTreeData = async (ctx) => {
    try {
        // 优化：只返回必要字段（假设前端只需要id、name、parentId等核心字段，按需调整）
        const group = await Group.findAll({
            attributes: ['id', 'name', 'parentId', 'type', 'edit'] // 显式指定字段，减少数据传输
        });
        sendResponse(ctx, 200, '查看成功', group);
    } catch (error) {
        console.error('getParentIdTreeData 错误:', error);
        sendResponse(ctx, 500, '查询失败', '查询失败');
    }
};

/**
 * 添加/编辑/删除分组
 */
const addEditDeleteGroup = async (ctx) => {
    try {
        const {id, ids, name, parentId, actionType} = ctx.request.body;

        if (actionType === 'create') {
            // 优化：显式指定创建字段，避免意外注入
            const group = await Group.create({
                name,
                parentId,
                type: 'group', // 固定值无需变量
                edit: 'true'
            });
            sendResponse(ctx, 200, '添加分组成功', group);
        } else if (actionType === 'edit') {
            // 优化：明确返回受影响行数的判断
            const [affectedCount] = await Group.update(
                {name, parentId},
                {where: {id}}
            );
            if (affectedCount > 0) {
                sendResponse(ctx, 200, '修改成功', '修改成功');
            } else {
                sendResponse(ctx, 500, '修改失败', '修改失败');
            }
        } else if (actionType === 'delete') {
            // 优化：批量删除（一次数据库操作替代循环多次操作）
            await Group.destroy({
                where: {id: ids} // 直接传数组，无需循环
            });
            sendResponse(ctx, 200, '删除成功', '删除成功');
        } else {
            sendResponse(ctx, 400, '无效的操作类型', '无效的actionType');
        }
    } catch (error) {
        console.error('addEditDeleteGroup 错误:', error);
        sendResponse(ctx, 500, '操作失败', '服务器异常');
    }
};

/**
 * 获取树形数据
 */
const getTreeData = async (ctx) => {
    try {
        await delayer(); // 使用默认延迟，保持前端交互节奏
        // 数据结构不变，保持原有返回
        sendResponse(ctx, 200, '查询成功', [
            {
                id: 1,
                name: "全部分组",
                type: "outer",
                edit: true,
                children: [
                    {
                        id: 2,
                        name: "默认单位",
                        type: "group",
                        edit: false,
                        children: [
                            {id: 3, name: "连队", type: "group", edit: false, children: []},
                            {id: 4, name: "副连部", type: "group", edit: false, children: []}
                        ]
                    },
                    {
                        id: 5,
                        name: "作战",
                        type: "group",
                        edit: true,
                        children: [
                            {id: 6, name: "侦察", type: "group", edit: true, children: []},
                            {id: 7, name: "火力", type: "group", edit: true, children: []},
                            {id: 8, name: "防爆", type: "group", edit: true, children: []}
                        ]
                    },
                    {
                        id: 9,
                        name: "后勤",
                        type: "group",
                        edit: true,
                        children: [
                            {id: 10, name: "炊事", type: "group", edit: true, children: []},
                            {id: 11, name: "保障", type: "group", edit: true, children: []}
                        ]
                    },
                    {id: 12, name: "电子对抗", type: "group", edit: true, children: []},
                    {id: 13, name: "防化", type: "group", edit: true, children: []},
                    {id: 14, name: "防核", type: "group", edit: true, children: []}
                ]
            }
        ]);
    } catch (error) {
        console.error('getTreeData 错误:', error);
        sendResponse(ctx, 500, '查询失败', '查询失败');
    }
};

/**
 * 获取概览数据
 */
const getOverview = async (ctx) => {
    try {
        await delayer(); // 保持延迟，不影响前端加载动画
        // 数据结构不变，保持原有返回
        sendResponse(ctx, 200, '查询成功', {
            center_list: [
                {
                    title: "当前活动任务",
                    p1_color: "#19BE6B",
                    p2_color: "#FF834B",
                    value: {
                        left: {title: "任务状态", p1: "正常:5", p1_value: 50, p2: "异常:5", p2_value: 50},
                        right: {
                            data: [{value: 5, name: "正常"}, {value: 5, name: "异常"}],
                            title: {
                                text: "10",
                                subtext: "任务数",
                                left: "center",
                                top: "center",
                                textStyle: {fontSize: 36},
                                subtextStyle: {fontSize: 12, color: "#9EA7B4", lineHeight: 0},
                                itemGap: 0
                            }
                        }
                    },
                    action: "active_task"
                },
                {
                    title: "客户端在线状态",
                    p1_color: "#19BE6B",
                    p2_color: "#949494",
                    value: {
                        left: {title: "客户端状态", p1: "在线:65", p1_value: 70, p2: "离线:35", p2_value: 30},
                        right: {
                            data: [{value: 65, name: "在线"}, {value: 22, name: "离线"}],
                            title: {
                                text: "97",
                                subtext: "客户端总数",
                                left: "center",
                                top: "center",
                                textStyle: {fontSize: 36},
                                subtextStyle: {fontSize: 12, color: "#9EA7B4", lineHeight: 0},
                                itemGap: 0
                            }
                        }
                    },
                    action: "client_status"
                },
                {
                    title: "已迁移客户端",
                    p1_color: "#19BE6B",
                    p2_color: "#FFC900",
                    value: {
                        left: {title: "客户端迁移详情", p1: "已完成迁移:65", p1_value: 70, p2: "未完成迁移:35", p2_value: 30},
                        right: {
                            data: [{value: 65, name: "已完成迁移"}, {value: 22, name: "未完成迁移"}],
                            title: {
                                text: "75%",
                                subtext: "迁移成功率",
                                left: "center",
                                top: "center",
                                textStyle: {fontSize: 36},
                                subtextStyle: {fontSize: 12, color: "#9EA7B4"},
                                itemGap: 0
                            }
                        }
                    },
                    action: "clients_migrated"
                }
            ],
            migration_data_compression: {compression_data: '20%', actual_data: "1000GB", to_migrated_data: "700GB"},
            migration_speed_list: [
                {title: "平均速度", id: "migration_speed_avg", value: "44.64"},
                {title: "最高速度", id: "migration_speed_max", value: "85.64"}
            ],
            migration_time_list: [
                {title: "平均耗时", value: "00:06:54"},
                {title: "最短耗时", value: "00:02:54"}
            ],
            helper_list: {
                quick_start: [
                    {name: " 准备迁移源机与迁移目标机", tab_id: "00", page_id: "00_00_01"},
                    {name: "  分别安装源机客户端与目标机客户端", tab_id: "01", page_id: "00_00_02"},
                    {name: "  配置从源机到目标机的迁移任务", tab_id: "02", page_id: "00_00_03"},
                    {name: "  同步源机数据到目标机中", tab_id: "03", page_id: "00_00_04"},
                    {name: "  迁移任务执行切换", tab_id: "04", page_id: "00_00_05"}
                ],
                problem_help: [
                    {name: "  如何安装迁移源机客户端", tab_id: "00", page_id: "00_00_01"},
                    {name: "   源机客户端安装失败", tab_id: "01", page_id: "00_00_02"},
                    {name: "   源机客户端安装后未上线到科力锐迁移云", tab_id: "02", page_id: "00_00_03"},
                    {name: "   如何在目标机中使用迁移启动介质", tab_id: "03", page_id: "00_00_04"},
                    {name: "   目标机以启动介质启动后未上线到科力锐迁移云", tab_id: "04", page_id: "00_00_05"},
                    {name: "   目标机匹配度是什么", tab_id: "00", page_id: "00_00_01"},
                    {name: "    选择不同匹配度的目标机做迁移任务有什么区别", tab_id: "01", page_id: "00_00_02"},
                    {name: "    迁移任务同步数据失败", tab_id: "02", page_id: "00_00_03"},
                    {name: "    迁移任务在同步数据阶段支持修改的任务配置", tab_id: "03", page_id: "00_00_04"},
                    {name: "    迁移任务切换前对源机处置策略执行失败", tab_id: "04", page_id: "00_00_05"},
                    {name: "     迁移任务切换失败", tab_id: "03", page_id: "00_00_04"},
                    {name: "     迁移任务切换完成后显示目标机离线", tab_id: "04", page_id: "00_00_05"}
                ]
            }
        });
    } catch (error) {
        console.error('getOverview 错误:', error);
        sendResponse(ctx, 500, '查询失败', '查询失败');
    }
};

/**
 * 错误测试接口
 */
const errorTest = async (ctx) => {
    sendResponse(ctx, 500, '查询失败', []); // 保持原有返回
};

/**
 * 获取文章列表（已优化）
 */
const getArticle = async (ctx) => {
    try {
        const {currentPage, pageSize, property, order, loopIds} = ctx.request.body;
        const {size, offset} = parsePagination(currentPage, pageSize);

        // 构建查询条件
        const whereCondition = loopIds ? {listId: {[Op.in]: loopIds}} : {};

        // 并行执行计数和查询（提升性能）
        const [total, article] = await Promise.all([
            Article.count({where: whereCondition}),
            Article.findAll({
                where: whereCondition,
                limit: size,
                offset: offset,
                order: property && order ? [[property, order]] : null,
                attributes: ['id', 'attr0', 'attr1', 'attr2', 'attr3', 'attr4', 'attr5', 'attr6', 'attr7', 'attr8', 'attr9', 'attr10', 'listId'] // 显式指定字段
            })
        ]);

        sendResponse(ctx, 200, '查看成功', {list: article, total});
    } catch (error) {
        console.error('getArticle 查询异常:', error);
        sendResponse(ctx, 500, '查询失败', '查询失败');
    }
};

/**
 * 添加文章（批量优化）
 */
const addArticle = async (ctx) => {
    try {
        const {loopCount = 1000000} = ctx.request.body;
        const count = Math.max(1, parseInt(loopCount, 10)); // 确保是有效数字

        // 优化：批量创建（替代循环逐条创建，性能提升10倍以上）
        const bulkData = [];
        for (let i = 0; i < count; i++) {
            bulkData.push({
                attr0: `attr0 测试假数据${i}`,
                attr1: `attr1 测试假数据${i}`,
                attr2: `attr2 测试假数据${i}`,
                attr3: `attr3 测试假数据${i}`,
                attr4: `attr4 测试假数据${i}`,
                attr5: `attr5 测试假数据${i}`,
                attr6: `attr6 测试假数据${i}`,
                attr7: `attr7 测试假数据${i}`,
                attr8: `attr8 测试假数据${i}`,
                attr9: `attr9 测试假数据${i}`,
                attr10: `attr10 测试假数据${i}`
            });
        }

        // 批量插入（注意：过大的批量可能需要分片，这里保持原有逻辑的count）
        await Article.bulkCreate(bulkData);
        sendResponse(ctx, 200, `创建数据集${count}条成功`, []);
    } catch (error) {
        console.error('addArticle 错误:', error);
        sendResponse(ctx, 500, `创建数据集${ctx.request.body.loopCount || 1000000}条失败`, []);
    }
};

/**
 * 测试接口
 */
const test = async (ctx) => {
    sendResponse(ctx, 200, "查看成功", {data: '联调成功'});
};

/**
 * 重定向到admin.html
 */
const toAdmin = async (ctx) => {
    ctx.status = 302;
    sendResponse(ctx, 200, "", '/admin.html', {redirect_url: '/admin.html'}); // 保持原有返回结构
};

// -------------------------- 路由配置（保持不变） --------------------------
const componentRoutes = [
    {type: 'post', url: '/component/getParentIdTreeData', method: getParentIdTreeData},
    {type: 'post', url: '/component/addEditDeleteGroup', method: addEditDeleteGroup},
    {type: 'post', url: '/component/getTreeData', method: getTreeData},
    {type: 'post', url: '/component/getOverview', method: getOverview},
    {type: 'post', url: '/component/errorTest', method: errorTest},
    {type: 'post', url: '/component/getArticle', method: getArticle},
    {type: 'post', url: '/component/addArticle', method: addArticle},
    {type: 'get', url: '/test', method: test},
    {type: 'get', url: '/toAdmin', method: toAdmin}
];

module.exports = componentRoutes;